﻿using SecurityApi.DataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SecurityApi.Business
{
    public class UserManager : IDisposable
    {
        private EnterpriseUserRepository _repository = new EnterpriseUserRepository();

        public bool UpdatePasswordInformation(string userName, string password, out string salt, int enterpriseId = 1)
        {
            PasswordHelper passwordHelper = new PasswordHelper();
            salt = passwordHelper.GenerateSalt();
            string hashedPassword = passwordHelper.EncodePassword(password, salt);
            return _repository.UpdatePasswordInformation(userName, hashedPassword, salt, enterpriseId);
        }


        public bool VerifyPassword(string userName, string password, int enterpriseId = 1)
        {
            bool bMatch = false;
            
            //Fetch existing password and salt
            SecurityApi.Model.EnterpriseUser user =  GetEnterpriseUser(userName ,enterpriseId);

            if (null != user)
            {
                PasswordHelper passwordHelper = new PasswordHelper();

                string salt = user.PasswordSalt;
                string hashedPassword = passwordHelper.EncodePassword(password, salt);

                if (hashedPassword == user.Password)
                {
                    bMatch = true;
                }
                else
                {
                    bMatch = false;
                }
            }
            return bMatch;
       
        }

        /// <summary>
        /// TODO: Password and salt should NOT leave the boundary.
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="enterpriseId"></param>
        /// <returns></returns>
        public SecurityApi.Model.EnterpriseUser GetEnterpriseUser(string userName, int enterpriseId = 1)
        {
            SecurityApi.Model.EnterpriseUser user = _repository.GetAll().Where(p => p.UserName == userName && p.EnterpriseId == enterpriseId).SingleOrDefault();
            return user;
        }

        public List<SecurityApi.Model.EnterpriseUser> GetEnterpriseUsers(int enterpriseId = 1)
        {
            List<SecurityApi.Model.EnterpriseUser> users = _repository.GetAll().ToList();
            return users;
        }
        public void Dispose()
        {
            _repository.Dispose();
        }

    }
}
